import {
	Injectable,
	NestInterceptor,
	ExecutionContext,
	CallHandler,
} from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { format } from "date-fns";

/**
 * 日期格式化拦截器
 * 用于将响应数据中的所有日期格式化为 yyyy-MM-dd HH:mm:ss
 */
@Injectable()
export class DateFormatInterceptor implements NestInterceptor {
	intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
		return next.handle().pipe(
			map((data) => {
				return this.formatDates(data);
			})
		);
	}

	/**
	 * 递归处理对象中的日期属性
	 */
	private formatDates(data: any): any {
		if (data === null || data === undefined) {
			return data;
		}

		if (data instanceof Date) {
			return format(data, "yyyy-MM-dd HH:mm:ss");
		}

		if (Array.isArray(data)) {
			return data.map((item) => this.formatDates(item));
		}

		if (typeof data === "object") {
			const result = {};

			for (const key of Object.keys(data)) {
				const value = data[key];
				result[key] = this.formatDates(value);
			}

			return result;
		}

		return data;
	}
}
